package com.charon.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import net.sf.json.JSONObject;


/**
 * @Description: 网络连接Handler
 * @Author charon [248135724@qq.com]
 * @Date:   2018年10月17日 下午6:35:11 
 * @version V1.0 
 */
@Slf4j
public class ConnectionHandler {
	public static final ThreadLocal<HashMap<String,String>> tl=new ThreadLocal<HashMap<String,String>>();
	
	/**
	 * 根据URL获取Dom
	 * @param url
	 * @return DOM树
	 */
	public static Document getResultDom(String url) {
		return Jsoup.parse(getResultStr(url));
	}
	
	/**
	 * 根据URL获取JSONObject
	 * @param url
	 * @return Json数据
	 */
	public static JSONObject getResultJson(String url) {
		String str = getResultStr(url);
		if(!StringUtils.isEmpty(str)){
			return null;
		}
		String strData=str.replaceAll(":null",":\"\"");
		if(str.length()>1000){
			log.info("网络结果："+str.substring(0,1000));
		}else{
			log.info("网络结果："+str);
		}
		return JSONObject.fromObject(strData);
	}
	
	/**
	 * 获取输出流
	 * @param url 访问地址
	 * @return 链接输出流
	 * @throws IOException
	 */
	public static InputStream getResultIS(String url) throws IOException {
		log.info("网络请求："+url);
		URL allUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) allUrl.openConnection(); // 设置协议头
		try {
			if (connection.getResponseCode() == 200 || connection.getResponseCode() == 302) {
				if(connection.getResponseCode() == 302){
					System.out.println("重定向:"+connection.getResponseMessage());
				}
				return connection.getInputStream();
			} else {
				log.error("链接：" + url + "  失败");
				log.error("状态码：" + connection.getResponseCode());
				HashMap<String,String> hash=new HashMap<String,String>();
				hash.put("链接",url);
				hash.put("状态码", connection.getResponseCode()+"");
				tl.set(hash);
			}
			return null;
		} catch (ConnectException e) {
			return null;
		}
	}
	
	/**
	 * @Description: 根据URL获取字符串
	 * @Author charon [248135724@qq.com]
	 * @Date:   2018年10月17日 下午7:31:19 
	 * @param url 访问地址
	 * @return 字符串
	 */
	public static String getResultStr(String url) {
		InputStream inputStream = null;
		StringBuffer allSB = null;
		try {
			inputStream = getResultIS(url);
			if (inputStream == null) {
				return "";
			}
			BufferedReader allBR = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			allSB = new StringBuffer("");
			String allL = null;
			while ((allL = allBR.readLine()) != null) {
				allSB.append(allL);
			}
			allBR.close();
		} catch (IOException e1) {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			e1.printStackTrace();
			return "";
		}
		return allSB.toString();
	}
	
}
